import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as path;
import 'package:file_picker/file_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart';
import 'dart:ui';

import '../AI/tina_dart/BaseAPI.dart';
import '../AI/dify_datasets.dart';
import '../AI/screen_shot_serve.dart';
import '../models/user_info.dart';
import '../serve/file_serve.dart';
import 'chat_page.dart';
import 'search_results_page.dart';
import 'upload_page.dart';
import '../serve/upload_service.dart';
import '../widgets/document_tags_widget.dart';
import '../widgets/docx_viewer_widget.dart';
import '../widgets/category_tags_widget.dart';
import '../widgets/enhanced_pdf_viewer.dart';
import '../widgets/enhanced_docx_viewer.dart';
import '../AI/smart_floating_ball_service.dart';

class HomePage extends StatefulWidget {
  final BaseAPI llm;
  final DifyKnowledgeDatabase difyKnowledge;
  final String appDataDir;
  final UserInfo userInfo;
  final FileServe fileServe;

  const HomePage({
    Key? key,
    required this.llm,
    required this.difyKnowledge,
    required this.appDataDir,
    required this.userInfo,
    required this.fileServe,
  }) : super(key: key);
  
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _greeting = '';
  String _aiMessage = '';
  bool _isLoading = true;
  bool _isTyping = false;
  List<Map<String, dynamic>> _knowledgeCards = [];
  int _refreshCounter = 0; // 添加刷新计数器
  String _sortMethod = '文档数量';
  final List<String> _sortOptions = ['文档数量', '查看次数', '首字母排序', '名称字数排序', '全部展开'];
  late FileServe _fileServe;
  late ScreenShotServe _screenShotServe;
  final ImagePicker _imagePicker = ImagePicker();
  late DifyKnowledgeDatabase _difyKnowledge;
  String _suggestion1 = '试着搜索知识库？';
  String _suggestion2 = '添加新文档吧！';
  String _suggestion3 = '和Tina聊聊天？';
  final UploadService _uploadService = UploadService();
  late SmartFloatingBallService _smartFloatingBallService;
  bool _isFloatingBallEnabled = false;
  StreamSubscription<SmartFloatingBallEvent>? _floatingBallEventSubscription;
  
  // 添加显示文本变量
  String _displaySuggestion1 = '';
  String _displaySuggestion2 = '';
  String _displaySuggestion3 = '';
  bool _isTypingSuggestion1 = false;
  bool _isTypingSuggestion2 = false;
  bool _isTypingSuggestion3 = false;

  @override
  void initState() {
    super.initState();
    _fileServe = widget.fileServe;
    _screenShotServe = ScreenShotServe(_fileServe);
    // 初始化显示文本
    _displaySuggestion1 = '';
    _displaySuggestion2 = '';
    _displaySuggestion3 = '';
    
    // 设置初始建议的空状态
    setState(() {
      _isTypingSuggestion1 = true;
      _isTypingSuggestion2 = true;
      _isTypingSuggestion3 = true;
    });
    
    // 监听上传服务状态变化
    _uploadService.addListener(_onUploadServiceChanged);
    
    _initialize();
  }

  @override
  void dispose() {
    _uploadService.removeListener(_onUploadServiceChanged);
    _floatingBallEventSubscription?.cancel();
    super.dispose();
  }
  
  // 悬浮球事件处理已移至全局监听器，此处不再需要

  void _onUploadServiceChanged() {
    if (mounted) {
      setState(() {
        // 触发UI更新以显示上传状态
      });
      
      // 检查是否有成功的上传，如果有则刷新知识卡片
      if (_uploadService.hasSuccessfulUploads()) {
        print('检测到成功的上传，准备刷新知识卡片');
        // 延迟一下再刷新，确保文件系统操作完成
        Future.delayed(Duration(seconds: 1), () {
          if (mounted) {
            _loadKnowledgeCards().then((_) {
              print('知识卡片刷新完成');
              // 清理已完成的任务
              _uploadService.clearCompletedTasks();
            });
          }
        });
      }
    }
  }

  Future<void> _initialize() async {
    try {
      print('开始初始化HomePage...');
      // FileServe已经在widget.fileServe中初始化
      
      // 初始化ScreenShotServe
      print('初始化截图服务...');
      await _screenShotServe.initialize(widget.llm);
      
      // 初始化上传服务
      print('初始化上传服务...');
      UploadService().initialize(
        llm: widget.llm,
        fileServe: widget.fileServe,
        difyKnowledge: widget.difyKnowledge,
        appDataDir: widget.appDataDir,
        screenShotServe: _screenShotServe,
        onUploadSuccess: () {
          // 上传成功后刷新知识卡片
          print('收到上传成功通知，刷新知识卡片');
          if (mounted) {
            _loadKnowledgeCards();
          }
        },
      );
      
      // 初始化智能悬浮球服务
      print('初始化智能悬浮球服务...');
      await SmartFloatingBallService.initialize();
      
      // 悬浮球事件现在由全局监听器处理，不再在页面级别监听
      
      print('正在加载知识卡片...');
      await _loadKnowledgeCards();
      
      if (!mounted) {
        print('组件已销毁，终止初始化过程');
        return;
      }
      
      print('设置问候语...');
      _setGreeting();
      
      print('获取AI问候...');
      await _getAIGreeting();
      
      print('HomePage初始化完成');
    } catch (e) {
      print('HomePage初始化失败: $e');
      
      if (!mounted) {
        print('组件已销毁，不执行setState');
        return;
      }
      
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _setGreeting() {
    final hour = DateTime.now().hour;
    if (hour < 6) {
      _greeting = '凌晨好';
    } else if (hour < 9) {
      _greeting = '早上好';
    } else if (hour < 12) {
      _greeting = '上午好';
    } else if (hour < 14) {
      _greeting = '中午好';
    } else if (hour < 18) {
      _greeting = '下午好';
    } else if (hour < 22) {
      _greeting = '晚上好';
    } else {
      _greeting = '夜深了';
    }
    
    if (widget.userInfo.nickname.isNotEmpty) {
      _greeting += '，${widget.userInfo.nickname}';
    }
  }

  Future<void> _getAIGreeting() async {
    // 检查组件是否仍然挂载
    if (!mounted) {
      print('组件已销毁，终止AI问候获取');
      return;
    }
    
    setState(() {
      _isTyping = true;
    });
    
    try {
      print('开始请求AI问候...');
      final _konwledgeCategory = await _fileServe.getKnowledgeCardInfo();
      final String _program_prompt = """
# 知拾使用指南

## 欢迎使用知拾!

这是您的个人知识库！你可以通过主页的加号来上传你的知识文档
除了支持docx，txt，md和pdf文档的上传
我们还支持使用图片上传你的文档！

看到一篇有用的知识，只需要截图或者拿起你的手机拍个照就可以自动地转化为你知识库里面的文档，不需要你过多地操作！
我们使用ocr技术和大模型来帮你整理图片里面的知识。

在主页上方的搜索框可以主动搜索你知识库里面的信息，也可以点击中间的知拾的logo和大模型聊天，大模型会主动的查询你的知识库来回答你的问题。

自定义你的身份，我们的大模型会根据你的身份给出合理的建议


## 主要功能

### 知识管理
- **文档上传**：支持多种格式的文档上传，包括PDF、TXT、DOCX、图片格式等。
- **自动分类**：系统会自动分析文档内容并进行分类整理。
- **知识卡片**：直观地展示您的知识库结构，方便快速查找。

### 智能问答
- **自然语言交互**：您可以用日常语言向系统提问。
- **知识库检索**：系统会自动从您的文档中找到最相关的信息。
- **智能推荐**：根据您的兴趣和使用习惯，提供个性化的知识推荐。

### 用户体验
- **个性化设置**：自定义您的身份标签和昵称。
- **聊天记录**：保存您与系统的对话历史，方便回顾。
- **多端同步**：计划支持多设备访问和同步（敬请期待）。

## 使用说明

1. **添加文档**：点击主页右下角的"+"按钮上传新文档。
2. **浏览知识库**：在主页底部的知识卡片中浏览您的文档。
3. **提问**：点击中央的图标开始与Tina对话。

""";
      final result = await widget.llm.predict(
        sysPrompt: '你是存在于知拾这个软件的智能助手，注意这是这个软件的说明：$_program_prompt，请你扮演Tina。用户名叫${widget.userInfo.nickname}，请根据当前时间，生成一个JSON格式的响应，包含问候语和三个建议。问候语在18个字以内。格式为: {"greeting":"问候语", "suggestion1":"第一个建议", "suggestion2":"第二个建议", "suggestion3":"第三个建议"}。针对用户标签的建议是这个意思：用户可能设置"学生"这样的身份标签，你需要思考学生使用我们软件是做什么的，可能需要什么样的建议，同样的对其他的身份标签也是一样的',
        inputText: '现在是${DateFormat('HH:mm').format(DateTime.now())}，请生成一句温柔的问候语和三个与知识库内容相关的建议。用户目前的知识库信息：${_konwledgeCategory.toString()}',
        temperature: 0.7
      );
      
      print('成功获取AI问候');
      
      // 检查组件是否仍然挂载
      if (!mounted) {
        print('组件已销毁，终止AI问候处理');
        return;
      }
      
      // 解析JSON格式的响应
      Map<String, dynamic> greetingData = {};
      try {
        // 获取返回内容中的JSON部分
        String content = result['content'] as String;
        // 提取JSON部分，处理可能的前缀和后缀文本
        RegExp jsonRegex = RegExp(r'({[\s\S]*})');
        var match = jsonRegex.firstMatch(content);
        if (match != null) {
          String jsonStr = match.group(1) ?? '';
          greetingData = json.decode(jsonStr);
          print('成功解析AI问候JSON格式: $greetingData');
        } else {
          print('无法从响应中提取JSON，使用默认值');
          greetingData = {
            'greeting': '欢迎回来！',
            'suggestion1': '搜索知识库',
            'suggestion2': '添加新文档',
            'suggestion3': '开始聊天'
          };
        }
      } catch (e) {
        print('解析AI问候JSON失败: $e，使用默认值');
        greetingData = {
          'greeting': '欢迎回来！',
          'suggestion1': '搜索知识库',
          'suggestion2': '添加新文档',
          'suggestion3': '开始聊天'
        };
      }
      
      // 更新建议文本
      _updateSuggestions(greetingData);
      
      // 模拟打字机效果显示问候语
      final message = greetingData['greeting'] as String? ?? '欢迎回来！';
      _simulateTyping(message);
    } catch (e) {
      print('获取AI问候失败: $e');
      
      // 检查组件是否仍然挂载
      if (!mounted) {
        print('组件已销毁，终止错误处理');
        return;
      }
      
      setState(() {
        _aiMessage = '欢迎回来！';
        _isTyping = false;
      });
    }
  }
  
  // 添加新方法：更新建议文本
  void _updateSuggestions(Map<String, dynamic> data) {
    setState(() {
      _suggestion1 = data['suggestion1'] as String? ?? '搜索知识库';
      _suggestion2 = data['suggestion2'] as String? ?? '添加新文档';
      _suggestion3 = data['suggestion3'] as String? ?? '开始聊天';
      
      // 启动打字机效果
      _startSuggestionTypingEffect();
    });
  }
  
  // 添加打字机效果方法
  void _startSuggestionTypingEffect() {
    // 重置显示文本，但保持打字中状态
    setState(() {
      _displaySuggestion1 = '';
      _displaySuggestion2 = '';
      _displaySuggestion3 = '';
      
      // 确保打字状态为true，显示空气泡
      _isTypingSuggestion1 = true;
      _isTypingSuggestion2 = true;
      _isTypingSuggestion3 = true;
    });
    
    // 第一个建议的打字机效果
    _simulateTypingForSuggestion(_suggestion1, 1);
    
    // 延迟后启动第二个建议的打字机效果
    Future.delayed(Duration(milliseconds: 800), () {
      if (mounted) {
        _simulateTypingForSuggestion(_suggestion2, 2);
      }
    });
    
    // 再次延迟后启动第三个建议的打字机效果
    Future.delayed(Duration(milliseconds: 1600), () {
      if (mounted) {
        _simulateTypingForSuggestion(_suggestion3, 3);
      }
    });
  }
  
  // 模拟打字效果的通用方法
  void _simulateTypingForSuggestion(String text, int suggestionNumber) {
    int index = 0;
    String currentText = '';
    
    // 设置打字中状态
    setState(() {
      switch (suggestionNumber) {
        case 1:
          _isTypingSuggestion1 = true;
          break;
        case 2:
          _isTypingSuggestion2 = true;
          break;
        case 3:
          _isTypingSuggestion3 = true;
          break;
      }
    });
    
    // 定时器模拟打字效果
    Future.doWhile(() async {
      if (!mounted) return false;
      
      if (index < text.length) {
        currentText += text[index];
        
        setState(() {
          switch (suggestionNumber) {
            case 1:
              _displaySuggestion1 = currentText;
              break;
            case 2:
              _displaySuggestion2 = currentText;
              break;
            case 3:
              _displaySuggestion3 = currentText;
              break;
          }
        });
        
        index++;
        await Future.delayed(Duration(milliseconds: 30)); // 稍快于问候语
        return true;
      } else {
        setState(() {
          switch (suggestionNumber) {
            case 1:
              _isTypingSuggestion1 = false;
              break;
            case 2:
              _isTypingSuggestion2 = false;
              break;
            case 3:
              _isTypingSuggestion3 = false;
              break;
          }
        });
        return false;
      }
    });
  }
  
  void _simulateTyping(String message) {
    int index = 0;
    String currentText = '';
    
    if (!mounted) {
      print('组件已销毁，终止打字效果');
      return;
    }
    
    setState(() {
      _aiMessage = '';
      _isTyping = true;
    });
    
    // 定时器模拟打字效果
    Future.doWhile(() async {
      if (!mounted) {
        print('组件已销毁，停止打字效果循环');
        return false;
      }
      
      if (index < message.length) {
        currentText += message[index];
        
        if (!mounted) {
          return false;
        }
        
        setState(() {
          _aiMessage = currentText;
        });
        index++;
        await Future.delayed(Duration(milliseconds: 50));
        return true;
      } else {
        if (!mounted) {
          return false;
        }
        
        setState(() {
          _isTyping = false;
        });
        return false;
      }
    });
  }

  Future<void> _loadKnowledgeCards() async {
    try {
      print('开始调用getKnowledgeCardInfo方法...');
      // 使用FileServe获取知识卡片数据
      final cardInfoList = await _fileServe.getKnowledgeCardInfo();
      print('获取知识卡片结果: ${cardInfoList.length}个分类');
      
      // 检查组件是否仍然挂载
      if (!mounted) {
        print('组件已销毁，终止操作');
        return;
      }
      
      if (cardInfoList.isEmpty) {
        print('没有知识卡片数据，创建软件说明类别...');
        // 如果没有获取到知识卡片数据，确保软件说明类别存在
        await _createSoftwareInfoCategory();
        
        // 检查组件是否仍然挂载
        if (!mounted) {
          print('组件已销毁，终止操作');
          return;
        }
        
        // 再次尝试获取
        print('再次尝试获取知识卡片...');
        final retryCardInfoList = await _fileServe.getKnowledgeCardInfo();
        print('重试获取结果: ${retryCardInfoList.length}个分类');
        
        // 再次检查组件是否仍然挂载
        if (!mounted) {
          print('组件已销毁，终止操作');
          return;
        }
        
        if (retryCardInfoList.isNotEmpty) {
          _processKnowledgeCards(retryCardInfoList);
        } else {
          print('无法加载任何知识卡片，设置空列表');
          setState(() {
            _knowledgeCards = [];
            _isLoading = false;
          });
        }
      } else {
        _processKnowledgeCards(cardInfoList);
      }
    } catch (e) {
      print('加载知识卡片失败: $e');
      print('加载知识卡片失败，堆栈: ${StackTrace.current}');
      
      // 检查组件是否仍然挂载
      if (!mounted) {
        print('组件已销毁，终止操作');
        return;
      }
      
      setState(() {
        _knowledgeCards = [];
        _isLoading = false;
      });
    }
  }
  
  void _processKnowledgeCards(List<Map<String, dynamic>> cardInfoList) {
    // 处理知识卡片数据
    List<Map<String, dynamic>> cards = [];
    
    for (var cardInfo in cardInfoList) {
      final categoryName = cardInfo['category'];
      final documents = cardInfo['documents'];
      
      cards.add({
        'category': categoryName,
        'documents': documents,
        'count': documents.length,
      });
    }
    
    // 排序
    _sortKnowledgeCards(cards);
    
    setState(() {
      _knowledgeCards = cards;
      _isLoading = false;
      _refreshCounter++; // 增加刷新计数器，强制标签组件刷新
    });
  }
  
  Future<void> _createSoftwareInfoCategory() async {
    try {
      print('开始创建软件说明类别...');
      // 获取about.md路径
      final docDir = Directory(path.join(widget.appDataDir, 'doc'));
      print('文档目录: ${docDir.path}');
      final dirExists = await docDir.exists();
      print('文档目录是否存在: $dirExists');
      
      if (!dirExists) {
        print('文档目录不存在，尝试创建');
        await docDir.create(recursive: true);
        print('文档目录创建完成');
      }
      
      final aboutFile = File(path.join(docDir.path, '知拾食用指南.md'));
      final aboutExists = await aboutFile.exists();
      print('知拾食用指南.md文件是否存在: $aboutExists，路径: ${aboutFile.path}');
      
      if (!aboutExists) {
        print('知拾食用指南.md文件不存在，创建默认文件');
        // 写入默认内容
        const defaultContent = '''
# 知拾使用指南

## 欢迎使用知拾!

这是您的个人知识库！你可以通过主页的加号来上传你的知识文档
除了支持docx，txt，md和pdf文档的上传
我们还支持使用图片上传你的文档！

看到一篇有用的知识，只需要截图或者拿起你的手机拍个照就可以自动地转化为你知识库里面的文档，不需要你过多地操作！
我们使用ocr技术和大模型来帮你整理图片里面的知识。

在主页上方的搜索框可以主动搜索你知识库里面的信息，也可以点击中间的知拾的logo和大模型聊天，大模型会主动的查询你的知识库来回答你的问题。

自定义你的身份，我们的大模型会根据你的身份给出合理的建议


## 主要功能

### 知识管理
- **文档上传**：支持多种格式的文档上传，包括PDF、TXT、DOCX、图片格式等。
- **自动分类**：系统会自动分析文档内容并进行分类整理。
- **知识卡片**：直观地展示您的知识库结构，方便快速查找。

### 智能问答
- **自然语言交互**：您可以用日常语言向系统提问。
- **知识库检索**：系统会自动从您的文档中找到最相关的信息。
- **智能推荐**：根据您的兴趣和使用习惯，提供个性化的知识推荐。

### 用户体验
- **个性化设置**：自定义您的身份标签和昵称。
- **聊天记录**：保存您与系统的对话历史，方便回顾。
- **多端同步**：计划支持多设备访问和同步（敬请期待）。

## 使用说明

1. **添加文档**：点击主页右下角的"+"按钮上传新文档。
2. **浏览知识库**：在主页底部的知识卡片中浏览您的文档。
3. **提问**：点击中央的图标开始与Tina对话。

''';
        await aboutFile.writeAsString(defaultContent);
        print('默认知拾食用指南.md文件创建成功');
      }
      
      // 创建"软件说明"分类
      final category = "软件说明";
      print('添加文档到文件系统: ${aboutFile.path}, 分类: $category');
      await _fileServe.addDocument(aboutFile.path, category);
      
      // 尝试创建Dify数据集
      print('尝试创建Dify数据集...');
      try {
        await widget.difyKnowledge.createDataset("知拾", "个人知识管理系统", aboutFile.path);
        print('Dify数据集创建成功');
        
        // 添加文档到Dify知识库并获取文档ID
        final uploadResult = await widget.difyKnowledge.addDocuments(aboutFile.path);
        
        // 从Dify响应中获取文档ID
        if (uploadResult != null) {
          final difyDocId = uploadResult["document"]?["id"] ?? "unknown_id";
          print('获取到Dify文档ID: $difyDocId');
          
          // 更新本地文档ID为Dify返回的ID
          await _fileServe.updateDocumentId(
            aboutFile.path,
            'temp_${DateTime.now().millisecondsSinceEpoch}', // 这是一个通配符，实际上会匹配任何临时ID
            difyDocId
          );
        }
      } catch (e) {
        print('创建Dify数据集或添加文档失败，但将继续处理: $e');
      }
      
      // 完成处理后刷新知识卡片信息
      // 通过FileServe的处理，文件已经成功添加到系统中
      // 不需要额外的缓存文件写入操作
      print('软件说明文档添加成功，下一步将更新知识卡片');
      
      // 刷新知识卡片
      if (mounted) {
        await _loadKnowledgeCards();
      }
    } catch (e) {
      print('创建软件说明类别失败: $e');
      print('创建软件说明类别失败，堆栈: ${StackTrace.current}');
    }
  }
  
  void _sortKnowledgeCards(List<Map<String, dynamic>> cards) {
    switch (_sortMethod) {
      case '文档数量':
        cards.sort((a, b) => b['count'].compareTo(a['count']));
        break;
      case '查看次数':
        // 这里可以实现按查看次数排序，需要记录查看次数
        cards.sort((a, b) => b['count'].compareTo(a['count']));
        break;
      case '首字母排序':
        cards.sort((a, b) => a['category'].toString().compareTo(b['category'].toString()));
        break;
      case '名称字数排序':
        cards.sort((a, b) => a['category'].toString().length.compareTo(b['category'].toString().length));
        break;
      case '全部展开':
        // 不需要排序，使用现有顺序
        break;
    }
  }
  
  Future<void> _uploadDocument() async {
    // 跳转到上传页面
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => UploadPage(
          llm: widget.llm,
          fileServe: _fileServe,
          difyKnowledge: widget.difyKnowledge,
          appDataDir: widget.appDataDir,
          screenShotServe: _screenShotServe,
        ),
      ),
    );
    
    // 如果有文件上传成功，刷新知识卡片
    if (result == true) {
      await _loadKnowledgeCards();
    }
  }

  /// 导航到上传页面并传递截图图片
  Future<void> _navigateToUploadWithImage(String imagePath) async {
    try {
      print('HomePage: 导航到上传页面，图片路径: $imagePath');
      
      // 跳转到上传页面，传递预选的图片路径
      final result = await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => UploadPage(
            llm: widget.llm,
            fileServe: _fileServe,
            difyKnowledge: widget.difyKnowledge,
            appDataDir: widget.appDataDir,
            screenShotServe: _screenShotServe,
            preSelectedImagePath: imagePath, // 传递截图路径
          ),
        ),
      );
      
      // 如果有文件上传成功，刷新知识卡片
      if (result == true) {
        await _loadKnowledgeCards();
      }
    } catch (e) {
      print('HomePage: 导航到上传页面失败 - $e');
      // 错误消息现在由全局消息处理
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('打开上传页面失败: $e'),
          backgroundColor: Colors.red[600],
        ),
      );
    }
  }


  // 显示分类选择对话框
  Future<String> _showCategorySelectionDialog(List<String> existingCategories, String suggestedCategory) async {
    String selectedCategory = suggestedCategory;
    String newCategory = '';
    bool useNewCategory = false;
    
    await showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: Text('选择或创建分类'),
              content: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('大模型建议的分类 "$suggestedCategory" 不在现有分类中。请选择一个分类或创建新分类:'),
                    SizedBox(height: 12),
                    // 现有分类列表
                    ...existingCategories.map((category) {
                      return RadioListTile<String>(
                        title: Text(category),
                        value: category,
                        groupValue: useNewCategory ? null : selectedCategory,
                        onChanged: (value) {
                          setState(() {
                            selectedCategory = value!;
                            useNewCategory = false;
                          });
                        },
                      );
                    }).toList(),
                    // 创建新分类选项
                    Divider(),
                    RadioListTile<String>(
                      title: Text('创建新分类'),
                      value: 'new',
                      groupValue: useNewCategory ? 'new' : null,
                      onChanged: (value) {
                        setState(() {
                          useNewCategory = true;
                          newCategory = suggestedCategory; // 默认使用建议的分类
                        });
                      },
                    ),
                    if (useNewCategory)
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 16.0),
                        child: TextField(
                          decoration: InputDecoration(
                            labelText: '新分类名称',
                            hintText: '输入分类名称',
                          ),
                          onChanged: (value) {
                            newCategory = value;
                          },
                          controller: TextEditingController(text: suggestedCategory),
                        ),
                      ),
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: Text('取消'),
                ),
                ElevatedButton(
                  onPressed: () {
                    Navigator.pop(context, true);
                  },
                  child: Text('确定'),
                ),
              ],
            );
          },
        );
      },
    ).then((confirmed) {
      if (confirmed == true) {
        if (useNewCategory && newCategory.isNotEmpty) {
          // 创建新分类
          _fileServe.addCategory(newCategory);
          return newCategory;
        } else {
          return selectedCategory;
        }
      }
      // 如果取消了对话框，使用原始分类
      return existingCategories.isNotEmpty ? existingCategories.first : '未分类';
    });
    
    if (useNewCategory && newCategory.isNotEmpty) {
      return newCategory;
    }
    return selectedCategory;
  }
  
  void _changeSortMethod() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('选择排序方式'),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: _sortOptions.map((method) {
                return RadioListTile<String>(
                  title: Text(method),
                  value: method,
                  groupValue: _sortMethod,
                  onChanged: (value) {
                    Navigator.pop(context);
                    setState(() {
                      _sortMethod = value!;
                      _sortKnowledgeCards(_knowledgeCards);
                    });
                  },
                );
              }).toList(),
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50], // 添加背景色
      body: _isLoading
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
              children: [
                  CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                  ),
                  SizedBox(height: 16),
                  Text(
                    '正在加载知识库...',
                    style: TextStyle(
                      color: Colors.grey[600],
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
            )
          : CustomScrollView(
              slivers: [
                // 美化的顶部区域
                SliverToBoxAdapter(
                  child: _buildBeautifulHeader(),
                ),
                // 美化的中间聊天区域
                SliverToBoxAdapter(
                  child: _buildChatSection(),
                ),
                // 美化的知识库标题
                SliverToBoxAdapter(
                  child: _buildKnowledgeLibraryHeader(),
                ),
                // 知识库卡片
                _sortMethod == '全部展开'
                    ? _buildExpandedKnowledgeSliver()
                    : _buildStackedKnowledgeCards(),
              ],
            ),
      floatingActionButton: _buildBeautifulFAB(),
    );
  }

  // 美化的顶部区域
  Widget _buildBeautifulHeader() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF667eea),
            Color(0xFF764ba2),
          ],
          stops: [0.0, 1.0],
        ),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(32),
          bottomRight: Radius.circular(32),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: SafeArea(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(24, 20, 24, 32),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 顶部状态栏
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // 问候语
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          _greeting,
                          style: TextStyle(
                            fontSize: 28,
                            fontWeight: FontWeight.w800,
                            color: Colors.white,
                            letterSpacing: 0.5,
                          ),
                        ),
                        SizedBox(height: 4),
                        Container(
                          height: 3,
                          width: 40,
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.8),
                            borderRadius: BorderRadius.circular(2),
                          ),
                        ),
                      ],
                    ),
                  ),

                  
                  // 上传状态指示器（优化样式）
                  if (_uploadService.activeTasksCount > 0) ...[
                    SizedBox(width: 8),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.15),
                        borderRadius: BorderRadius.circular(20),
                        border: Border.all(
                          color: Colors.white.withOpacity(0.3),
                          width: 1,
                        ),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(
                            width: 16,
                            height: 16,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                            ),
                          ),
                          SizedBox(width: 8),
                          Text(
                            '${_uploadService.activeTasksCount}个任务',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 13,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ],
              ),
              
              SizedBox(height: 20),
              
              // AI消息容器（美化）
              Container(
                constraints: BoxConstraints(minHeight: 32),
                child: AnimatedContainer(
                  duration: Duration(milliseconds: 300),
                  padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.15),
                    borderRadius: BorderRadius.circular(16),
                    border: Border.all(
                      color: Colors.white.withOpacity(0.2),
                      width: 1,
                    ),
                  ),
                  child: Row(
                    children: [
                      Icon(
                        Icons.auto_awesome,
                        color: Colors.white.withOpacity(0.9),
                        size: 18,
                      ),
                      SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          _aiMessage.isEmpty ? '正在思考中...' : _aiMessage,
                          style: TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.w500,
                            color: Colors.white.withOpacity(0.95),
                            height: 1.3,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              
              SizedBox(height: 24),
              
              // 美化的搜索框 - 用RepaintBoundary分离，优化性能
              RepaintBoundary(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(28),
                    // 简化阴影以提升性能
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.08),
                        blurRadius: 12,
                        offset: Offset(0, 6),
                      ),
                    ],
                  ),
                  child: TextField(
                    decoration: InputDecoration(
                      hintText: '🔍 搜索知识库中的内容...',
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                      hintStyle: TextStyle(
                        color: Colors.grey[400],
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                      suffixIcon: Container(
                        margin: EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                          ),
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: Icon(
                          Icons.search,
                          color: Colors.white,
                          size: 20,
                        ),
                      ),
                    ),
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                    textInputAction: TextInputAction.search,
                    onSubmitted: (query) {
                      if (query.trim().isNotEmpty) {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => SearchResultsPage(
                              query: query.trim(),
                              difyKnowledge: widget.difyKnowledge,
                              fileServe: _fileServe,
                            ),
                          ),
                        );
                      }
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 美化的聊天区域
  Widget _buildChatSection() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 24, vertical: 32),
                        child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
          // 应用Logo（装饰性）
          Container(
              width: 88,
              height: 88,
                              decoration: BoxDecoration(
                                color: Colors.white,
                                shape: BoxShape.circle,
                                boxShadow: [
                                  BoxShadow(
                    color: Colors.blue.withOpacity(0.2),
                    blurRadius: 20,
                    offset: Offset(0, 8),
                  ),
                  BoxShadow(
                    color: Colors.blue.withOpacity(0.1),
                    blurRadius: 40,
                    offset: Offset(0, 16),
                  ),
                ],
                border: Border.all(
                  color: Colors.blue.withOpacity(0.1),
                  width: 2,
                ),
              ),
              child: Stack(
                children: [
                  Center(
                              child: ClipOval(
                                child: Image.asset(
                                  'assets/images/logo.png',
                        width: 72,
                        height: 72,
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                  // 添加一个微妙的光环效果
                  Positioned.fill(
                    child: Container(
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        gradient: RadialGradient(
                          center: Alignment.topLeft,
                          radius: 1.0,
                          colors: [
                            Colors.white.withOpacity(0.3),
                            Colors.transparent,
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          
          SizedBox(width: 24),
          
          // 美化的建议气泡
          Expanded(
                              child: Column(
                                children: [
                _buildBeautifulSuggestionBubble(
                                    _displaySuggestion1, 
                  LinearGradient(
                    colors: [Color(0xFFE3F2FD), Color(0xFFBBDEFB)],
                  ),
                                    Icons.lightbulb_outline,
                                    () {
                                      if (!_isTypingSuggestion1 && _displaySuggestion1.isNotEmpty) {
                                        _navigateToChatWithSuggestion(_suggestion1);
                                      }
                                    },
                                    isTyping: _isTypingSuggestion1,
                                  ),
                SizedBox(height: 12),
                _buildBeautifulSuggestionBubble(
                                    _displaySuggestion2, 
                  LinearGradient(
                    colors: [Color(0xFFFFF8E1), Color(0xFFFFE0B2)],
                  ),
                                    Icons.tips_and_updates_outlined,
                                    () {
                                      if (!_isTypingSuggestion2 && _displaySuggestion2.isNotEmpty) {
                                        _navigateToChatWithSuggestion(_suggestion2);
                                      }
                                    },
                                    isTyping: _isTypingSuggestion2,
                                  ),
                SizedBox(height: 12),
                _buildBeautifulSuggestionBubble(
                                    _displaySuggestion3, 
                  LinearGradient(
                    colors: [Color(0xFFF3E5F5), Color(0xFFE1BEE7)],
                  ),
                                    Icons.psychology_outlined,
                                    () {
                                      if (!_isTypingSuggestion3 && _displaySuggestion3.isNotEmpty) {
                                        _navigateToChatWithSuggestion(_suggestion3);
                                      }
                                    },
                                    isTyping: _isTypingSuggestion3,
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
    );
  }

  // 美化的建议气泡
  Widget _buildBeautifulSuggestionBubble(
    String text,
    Gradient gradient,
    IconData icon,
    VoidCallback onTap,
    {bool isTyping = false}
  ) {
    return AnimatedContainer(
      duration: Duration(milliseconds: 300),
      curve: Curves.easeOut,
      decoration: BoxDecoration(
        gradient: gradient,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.06),
            blurRadius: 12,
            offset: Offset(0, 4),
          ),
        ],
        border: Border.all(
          color: Colors.white.withOpacity(0.5),
          width: 1,
        ),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: text.isNotEmpty ? onTap : null,
          borderRadius: BorderRadius.circular(20),
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Row(
              children: [
                Container(
                  padding: EdgeInsets.all(6),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.7),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(
                    icon,
                    size: 16,
                    color: Colors.grey[700],
                  ),
                ),
                SizedBox(width: 12),
                Expanded(
                  child: text.isEmpty && !isTyping
                      ? Row(
                          children: [
                            Text(
                              "正在思考...",
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w500,
                                color: Colors.grey[600],
                                fontStyle: FontStyle.italic,
                              ),
                            ),
                            SizedBox(width: 8),
                            SizedBox(
                              width: 12,
                              height: 12,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[500]!),
                              ),
                            ),
                          ],
                        )
                      : Row(
                          children: [
                            Expanded(
                              child: Text(
                                text,
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.grey[800],
                                  height: 1.3,
                                ),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            if (isTyping && text.isNotEmpty)
                              Container(
                                width: 2,
                                height: 16,
                                margin: EdgeInsets.only(left: 4),
                                decoration: BoxDecoration(
                                  color: Colors.grey[600],
                                  borderRadius: BorderRadius.circular(1),
                                ),
                              ),
                          ],
                        ),
                ),
                if (!isTyping && text.isNotEmpty)
                  Container(
                    padding: EdgeInsets.all(4),
                    child: Icon(
                      Icons.arrow_forward_ios,
                      size: 12,
                      color: Colors.grey[600],
                    ),
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 美化的知识库标题
  Widget _buildKnowledgeLibraryHeader() {
    return Container(
      padding: EdgeInsets.fromLTRB(24, 8, 24, 16),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
          Row(
            children: [
              Container(
                padding: EdgeInsets.all(8),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                  ),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(
                  Icons.library_books,
                  color: Colors.white,
                  size: 20,
                ),
              ),
              SizedBox(width: 12),
                            Text(
                              '知识库',
                style: TextStyle(
                  fontSize: 22,
                  fontWeight: FontWeight.w700,
                  color: Colors.grey[800],
                ),
              ),
            ],
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 8,
                  offset: Offset(0, 2),
                ),
              ],
            ),
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: _changeSortMethod,
                borderRadius: BorderRadius.circular(16),
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                              child: Row(
                    mainAxisSize: MainAxisSize.min,
                                children: [
                      Icon(
                        Icons.sort,
                        size: 18,
                        color: Colors.grey[600],
                      ),
                      SizedBox(width: 6),
                      Text(
                        _sortMethod,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                          color: Colors.grey[700],
                        ),
                      ),
                      SizedBox(width: 4),
                      Icon(
                        Icons.arrow_drop_down,
                        size: 18,
                        color: Colors.grey[600],
                            ),
                          ],
                        ),
                      ),
              ),
            ),
                      ),
                    ],
                  ),
    );
  }

  // 美化的浮动按钮
  Widget _buildBeautifulFAB() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFF667eea), Color(0xFF764ba2)],
        ),
        borderRadius: BorderRadius.circular(28),
        boxShadow: [
          BoxShadow(
            color: Color(0xFF667eea).withOpacity(0.3),
            blurRadius: 20,
            offset: Offset(0, 8),
                ),
              ],
            ),
      child: FloatingActionButton(
        onPressed: _uploadDocument,
        backgroundColor: Colors.transparent,
        elevation: 0,
        child: Icon(
          Icons.add,
          color: Colors.white,
          size: 28,
        ),
        tooltip: '上传文档或图片',
      ),
    );
  }

  Widget _buildStackedKnowledgeCards() {
    final List<List<Color>> gradientColors = [
      [Color(0xFFE8EAF6), Color(0xFFC5CAE9)], // 紫色系
      [Color(0xFFE3F2FD), Color(0xFFBBDEFB)], // 蓝色系
      [Color(0xFFE0F2F1), Color(0xFFB2DFDB)], // 青色系
      [Color(0xFFFFF8E1), Color(0xFFFFE0B2)], // 琥珀色系
      [Color(0xFFFCE4EC), Color(0xFFF8BBD9)], // 粉色系
      [Color(0xFFE8F5E8), Color(0xFFC8E6C9)], // 绿色系
      [Color(0xFFFFF3E0), Color(0xFFFFCC02)], // 橙色系
      [Color(0xFFFFEBEE), Color(0xFFFFCDD2)], // 红色系
    ];

    return SliverPadding(
      padding: EdgeInsets.fromLTRB(24, 0, 24, 100), // 为FAB留出空间
      sliver: SliverList(
        delegate: SliverChildBuilderDelegate(
          (context, index) {
        final card = _knowledgeCards[index];
        final documents = card['documents'] as List;
            final colors = gradientColors[index % gradientColors.length];
        
        return Container(
              margin: EdgeInsets.only(bottom: 20),
          child: GestureDetector(
            onTap: () async {
              final result = await Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => CategoryDetailPage(
                    category: card['category'],
                    documents: List<Map<String, dynamic>>.from(documents),
                    difyKnowledge: widget.difyKnowledge,
                    fileServe: _fileServe,
                    llm: widget.llm,
                    userInfo: widget.userInfo,
                  ),
                ),
              );
              
              if (result == true) {
                await _loadKnowledgeCards();
              }
            },
                child: Container(
                      decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: colors,
                    ),
                    borderRadius: BorderRadius.circular(20),
                    boxShadow: [
                      BoxShadow(
                        color: colors[1].withOpacity(0.3),
                        blurRadius: 16,
                        offset: Offset(0, 8),
                      ),
                    ],
                    border: Border.all(
                      color: Colors.white.withOpacity(0.3),
                      width: 1,
                    ),
                  ),
                  child: Padding(
                    padding: EdgeInsets.all(20),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Text(
                                card['category'],
                                style: TextStyle(
                                  fontSize: 20,
                                  fontWeight: FontWeight.w700,
                                  color: Colors.grey[800],
                                ),
                                ),
                              ),
                              Container(
                              padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                                decoration: BoxDecoration(
                                color: Colors.white.withOpacity(0.8),
                                borderRadius: BorderRadius.circular(16),
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.black.withOpacity(0.05),
                                    blurRadius: 4,
                                    offset: Offset(0, 2),
                                  ),
                                ],
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.description,
                                    size: 14,
                                    color: Colors.grey[600],
                                  ),
                                  SizedBox(width: 4),
                                  Text(
                                    '${card['count']}',
                                  style: TextStyle(
                                      fontSize: 13,
                                      fontWeight: FontWeight.w600,
                                      color: Colors.grey[700],
                                  ),
                                  ),
                                ],
                                ),
                              ),
                            ],
                          ),
                        
                        SizedBox(height: 16),
                        
                        // 分类标签
                        CategoryTagsWidget(
                          key: ValueKey('${card['category']}_$_refreshCounter'),
                              category: card['category'],
                              fileServe: _fileServe,
                          maxDisplayTags: 3,
                        ),
                        
                        SizedBox(height: 12),
                        
                        // 文档预览
                          if (documents.isNotEmpty)
                          Container(
                            padding: EdgeInsets.all(12),
                            decoration: BoxDecoration(
                              color: Colors.white.withOpacity(0.7),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Icon(
                                      Icons.folder_open,
                                      size: 16,
                                      color: Colors.grey[600],
                                    ),
                                    SizedBox(width: 6),
                                    Text(
                                      '包含文档',
                                style: TextStyle(
                                        fontSize: 12,
                                        fontWeight: FontWeight.w600,
                                  color: Colors.grey[600],
                                      ),
                                    ),
                                  ],
                                ),
                                SizedBox(height: 6),
                                Text(
                                  documents.take(3).map((doc) => doc['title']).join(' • ') +
                                      (documents.length > 3 ? ' ...' : ''),
                                  style: TextStyle(
                                    fontSize: 14,
                                    color: Colors.grey[700],
                                    height: 1.3,
                                ),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                ),
                              ],
                              ),
                            )
                          else
                          Container(
                            padding: EdgeInsets.all(12),
                            decoration: BoxDecoration(
                              color: Colors.white.withOpacity(0.5),
                              borderRadius: BorderRadius.circular(12),
                              border: Border.all(
                                color: Colors.grey.withOpacity(0.2),
                                style: BorderStyle.solid,
                              ),
                            ),
                            child: Row(
                              children: [
                                Icon(
                                  Icons.inbox,
                                  size: 16,
                                  color: Colors.grey[500],
                                ),
                                SizedBox(width: 8),
                            Text(
                              '暂无文档',
                              style: TextStyle(
                                fontSize: 14,
                                    color: Colors.grey[500],
                                    fontStyle: FontStyle.italic,
                              ),
                            ),
                        ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          ),
        );
      },
          childCount: _knowledgeCards.length,
        ),
      ),
    );
  }

  // 美化的展开视图
  SliverList _buildExpandedKnowledgeSliver() {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) {
        final card = _knowledgeCards[index];
        final documents = card['documents'] as List;
          
          return Container(
            margin: EdgeInsets.fromLTRB(24, 0, 24, 24),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 12,
                  offset: Offset(0, 4),
                ),
              ],
            ),
            child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
                // 分类标题
                Container(
                  padding: EdgeInsets.all(20),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Color(0xFFF8F9FA), Color(0xFFE9ECEF)],
                    ),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(16),
                      topRight: Radius.circular(16),
                    ),
                  ),
                  child: Row(
                    children: [
                      Container(
                        padding: EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                          ),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Icon(
                          Icons.folder,
                          color: Colors.white,
                          size: 16,
                        ),
                      ),
                      SizedBox(width: 12),
                      Expanded(
              child: Text(
                card['category'],
                style: TextStyle(
                  fontSize: 18,
                            fontWeight: FontWeight.w700,
                            color: Colors.grey[800],
                ),
              ),
            ),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          color: Colors.blue.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          '${documents.length} 文档',
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w500,
                            color: Colors.blue[700],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                
                // 文档列表
                if (documents.isNotEmpty)
                  ...documents.asMap().entries.map((entry) {
                    final docIndex = entry.key;
                    final doc = entry.value;
                    final isLast = docIndex == documents.length - 1;
                    
                    return Container(
                      decoration: BoxDecoration(
                        border: !isLast ? Border(
                          bottom: BorderSide(
                            color: Colors.grey[200]!,
                            width: 1,
                          ),
                        ) : null,
                      ),
                      child: ListTile(
                        contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 8),
                        leading: Container(
                          padding: EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: Colors.blue.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Icon(
                            Icons.description,
                            color: Colors.blue[600],
                            size: 20,
                          ),
                        ),
                        title: Text(
                          doc['title'],
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            fontSize: 15,
                          ),
                        ),
                subtitle: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                            SizedBox(height: 4),
                            Text(
                              '文件名: ${path.basename(doc['path'] ?? 'unknown')}',
                              style: TextStyle(
                                fontSize: 13,
                                color: Colors.grey[600],
                              ),
                            ),
                            SizedBox(height: 4),
                    CompactDocumentTagsWidget(document: doc),
                  ],
                ),
                        trailing: Icon(
                          Icons.arrow_forward_ios,
                          size: 16,
                          color: Colors.grey[400],
                        ),
                onTap: () async {
                  final result = await Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => DocumentDetailPage(
                        document: Map<String, dynamic>.from(doc),
                        difyKnowledge: widget.difyKnowledge,
                        fileServe: _fileServe,
                        llm: widget.llm,
                        userInfo: widget.userInfo,
                      ),
                    ),
                  );
                  
                  if (result == true) {
                    await _loadKnowledgeCards();
                  }
                },
                      ),
                    );
                  }).toList()
                else
                  Container(
                    padding: EdgeInsets.all(32),
                    child: Center(
                      child: Column(
              children: [
                          Icon(
                            Icons.inbox,
                            size: 48,
                            color: Colors.grey[300],
                          ),
                          SizedBox(height: 8),
                                  Text(
                            '该分类下暂无文档',
                                    style: TextStyle(
                              color: Colors.grey[500],
                                      fontSize: 14,
                                    ),
                                  ),
                                ],
                      ),
                    ),
                        ),
                    ],
                  ),
          );
        },
        childCount: _knowledgeCards.length,
      ),
    );
  }

  // 添加导航到聊天界面的方法
  void _navigateToChatWithSuggestion(String suggestion) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ChatPage(
          llm: widget.llm,
          difyKnowledge: widget.difyKnowledge,
          appDataDir: widget.appDataDir,
          userInfo: widget.userInfo,
          fileServe: widget.fileServe,
          initialMessage: suggestion,
        ),
      ),
    );
  }
}

// 分类详情页面
class CategoryDetailPage extends StatelessWidget {
  final String category;
  final List<Map<String, dynamic>> documents;
  final DifyKnowledgeDatabase difyKnowledge;
  final FileServe fileServe;
  final BaseAPI? llm;
  final UserInfo? userInfo;

  const CategoryDetailPage({
    Key? key,
    required this.category,
    required this.documents,
    required this.difyKnowledge,
    required this.fileServe,
    this.llm,
    this.userInfo,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: Column(
        children: [
          // 美化的顶部区域
          _buildBeautifulHeader(context),
          // 文档列表
          Expanded(
            child: documents.isEmpty
                ? _buildEmptyState()
                : _buildDocumentList(),
          ),
        ],
      ),
    );
  }

  Widget _buildBeautifulHeader(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF667eea),
            Color(0xFF764ba2),
          ],
        ),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(32),
          bottomRight: Radius.circular(32),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: SafeArea(
        child: Padding(
          padding: EdgeInsets.fromLTRB(20, 8, 20, 24),
          child: Column(
            children: [
              // 顶部导航栏
              Row(
                children: [
                  // 返回按钮
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: IconButton(
                      icon: Icon(Icons.arrow_back, color: Colors.white),
                      onPressed: () => Navigator.pop(context),
                    ),
                  ),
                  
                  SizedBox(width: 12),
                  
                  // 分类图标
                  Container(
                    padding: EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Icon(
                      Icons.folder_outlined,
                      color: Colors.white,
                      size: 24,
                    ),
                  ),
                  
                  SizedBox(width: 12),
                  
                  // 分类标题
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          category,
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w700,
                            color: Colors.white,
                            letterSpacing: 0.3,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        SizedBox(height: 2),
                        Text(
                          '${documents.length} 个文档',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.white.withOpacity(0.8),
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              
              SizedBox(height: 20),
              
              // 分类标签区域
              Container(
                padding: EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.15),
                  borderRadius: BorderRadius.circular(16),
                  border: Border.all(color: Colors.white.withOpacity(0.2)),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.local_offer, size: 16, color: Colors.white),
                        SizedBox(width: 8),
                        Text(
                          '分类标签',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 12),
                    CategoryTagsWidget(
                      key: ValueKey('${category}_detail_${DateTime.now().millisecondsSinceEpoch}'),
                      category: category,
                      fileServe: fileServe,
                      maxDisplayTags: 10,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Container(
      padding: EdgeInsets.all(32),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              padding: EdgeInsets.all(24),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(20),
                border: Border.all(color: Colors.grey[200]!),
              ),
              child: Icon(
                Icons.folder_open_outlined,
                size: 64,
                color: Colors.grey[400],
              ),
            ),
            SizedBox(height: 24),
            Text(
              '该分类下暂无文档',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
                color: Colors.grey[600],
              ),
            ),
            SizedBox(height: 8),
            Text(
              '开始上传文档来充实您的知识库吧',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[500],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDocumentList() {
    return ListView.builder(
      itemCount: documents.length,
      padding: EdgeInsets.all(24),
      itemBuilder: (context, index) {
        final doc = documents[index];
        return Container(
          margin: EdgeInsets.only(bottom: 16),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.08),
                blurRadius: 16,
                offset: Offset(0, 8),
              ),
            ],
          ),
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              borderRadius: BorderRadius.circular(20),
              onTap: () async {
                final result = await Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DocumentDetailPage(
                      document: doc,
                      difyKnowledge: difyKnowledge,
                      fileServe: fileServe,
                      llm: llm,
                      userInfo: userInfo,
                    ),
                  ),
                );
                
                // 如果文档被删除，则刷新页面
                if (result == true && context.mounted) {
                  Navigator.pop(context, true); // 通知上级页面刷新
                }
              },
              child: Padding(
                padding: EdgeInsets.all(20),
                child: Row(
                  children: [
                    // 文档图标
                    Container(
                      padding: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [
                            Color(0xFF667eea).withOpacity(0.1),
                            Color(0xFF764ba2).withOpacity(0.1),
                          ],
                        ),
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Icon(
                        _getDocumentIcon(doc['path']),
                        color: Color(0xFF667eea),
                        size: 24,
                      ),
                    ),
                    
                    SizedBox(width: 16),
                    
                    // 文档信息
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            doc['title'] ?? '未知文档',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: Colors.grey[800],
                              letterSpacing: 0.3,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          SizedBox(height: 6),
                          Text(
                            '文件名: ${path.basename(doc['path'] ?? 'unknown')}',
                            style: TextStyle(
                              fontSize: 13,
                              color: Colors.grey[600],
                              fontWeight: FontWeight.w500,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          if (doc['time'] != null) ...[
                            SizedBox(height: 4),
                            Row(
                              children: [
                                Icon(Icons.access_time, size: 12, color: Colors.grey[500]),
                                SizedBox(width: 4),
                                Text(
                                  _formatDateTime(doc['time']),
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Colors.grey[500],
                                  ),
                                ),
                              ],
                            ),
                          ],
                          SizedBox(height: 8),
                          CompactDocumentTagsWidget(document: doc),
                        ],
                      ),
                    ),
                    
                    // 箭头图标
                    Container(
                      padding: EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        color: Colors.grey[100],
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Icon(
                        Icons.arrow_forward_ios,
                        size: 16,
                        color: Colors.grey[500],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  IconData _getDocumentIcon(String? filePath) {
    if (filePath == null) return Icons.description;
    final lowerPath = filePath.toLowerCase();
    if (lowerPath.endsWith('.pdf')) return Icons.picture_as_pdf;
    if (lowerPath.endsWith('.docx')) return Icons.description;
    if (lowerPath.endsWith('.md')) return Icons.code;
    if (lowerPath.endsWith('.txt')) return Icons.text_fields;
    return Icons.description;
  }
  
  String _formatDateTime(String dateTimeString) {
    try {
      final dateTime = DateTime.parse(dateTimeString);
      return DateFormat('yyyy-MM-dd HH:mm').format(dateTime);
    } catch (e) {
      return dateTimeString;
    }
  }
}

// 文档详情页面
class DocumentDetailPage extends StatefulWidget {
  final Map<String, dynamic> document;
  final DifyKnowledgeDatabase difyKnowledge;
  final FileServe fileServe;
  final BaseAPI? llm;
  final UserInfo? userInfo;

  const DocumentDetailPage({
    Key? key,
    required this.document,
    required this.difyKnowledge,
    required this.fileServe,
    this.llm,
    this.userInfo,
  }) : super(key: key);

  @override
  _DocumentDetailPageState createState() => _DocumentDetailPageState();
}

class _DocumentDetailPageState extends State<DocumentDetailPage> {
  bool _isLoading = true;
  String _documentContent = '';
  bool _isPdfFile = false;
  bool _isDocxFile = false;
  bool _isMarkdownFile = false;
  String? _filePath;
  Map<String, dynamic> _currentDocument = {}; // 添加可变的文档数据

  @override
  void initState() {
    super.initState();
    _currentDocument = Map<String, dynamic>.from(widget.document); // 初始化可变文档数据
    _loadDocumentContent();
  }

  Future<void> _loadDocumentContent() async {
    try {
      final filePath = _currentDocument['path'];
      _filePath = filePath;
      
      if (filePath != null) {
        final file = File(filePath);
        if (await file.exists()) {
          // 检查文件类型
          final lowerPath = filePath.toLowerCase();
          if (lowerPath.endsWith('.pdf')) {
            setState(() {
              _isPdfFile = true;
              _isLoading = false;
            });
            return;
          } else if (lowerPath.endsWith('.docx')) {
            setState(() {
              _isDocxFile = true;
              _documentContent = '暂不支持直接查看DOCX文件内容。\n\n建议：\n1. 将文档转换为PDF或TXT格式\n2. 使用知识库搜索功能查找相关内容\n3. 通过聊天功能让AI读取文档内容';
              _isLoading = false;
            });
            return;
          } else if (lowerPath.endsWith('.md')) {
            _isMarkdownFile = true;
          }
          
          final content = await file.readAsString();
          setState(() {
            _documentContent = content;
            _isLoading = false;
          });
        } else {
          setState(() {
            _documentContent = '文件不存在或已被移除';
            _isLoading = false;
          });
        }
      } else {
        // 尝试使用文档ID从知识库查询内容
        final docId = widget.document['doc_id'];
        if (docId != null) {
          try {
            final docPath = await widget.difyKnowledge.getDocumentPath(docId);
            if (docPath != null) {
              final file = File(docPath);
              if (await file.exists()) {
                final content = await file.readAsString();
                setState(() {
                  _documentContent = content;
                  _isLoading = false;
                });
                return;
              }
            }
            
            // 通过知识库查询内容
            final queryResult = await widget.difyKnowledge.query(widget.document['title']);
            if (queryResult.isNotEmpty) {
              setState(() {
                _documentContent = queryResult.map((item) => item['content']).join('\n\n---\n\n');
                _isLoading = false;
              });
            } else {
              setState(() {
                _documentContent = '无法获取文档内容';
                _isLoading = false;
              });
            }
          } catch (e) {
            setState(() {
              _documentContent = '加载文档内容失败: $e';
              _isLoading = false;
            });
          }
        } else {
          setState(() {
            _documentContent = '无法获取文档内容：缺少路径和文档ID';
            _isLoading = false;
          });
        }
      }
    } catch (e) {
      print('加载文档内容失败: $e');
      setState(() {
        _documentContent = '加载文档内容失败: $e';
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: Column(
        children: [
          // 美化的顶部区域
          _buildBeautifulHeader(),
          // 文档内容区域
          Expanded(
            child: _isLoading
                ? _buildLoadingView()
                : _isPdfFile
                    ? _buildPdfViewer()
                    : _isDocxFile
                        ? _buildDocxViewer()
                        : _buildDocumentContent(),
          ),
        ],
      ),
    );
  }

  Widget _buildBeautifulHeader() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF667eea),
            Color(0xFF764ba2),
          ],
        ),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(32),
          bottomRight: Radius.circular(32),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: SafeArea(
        child: Padding(
          padding: EdgeInsets.fromLTRB(20, 8, 20, 20),
          child: Column(
            children: [
              // 顶部导航栏
              Row(
                children: [
                  // 返回按钮
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: IconButton(
                      icon: Icon(Icons.arrow_back, color: Colors.white),
                      onPressed: () => Navigator.pop(context),
                    ),
                  ),
                  
                  SizedBox(width: 12),
                  
                  // 文档图标
                  Container(
                    padding: EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Icon(
                      _getFileIcon(),
                      color: Colors.white,
                      size: 24,
                    ),
                  ),
                  
                  SizedBox(width: 12),
                  
                  // 文档标题
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          widget.document['title'] ?? '未知文档',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w700,
                            color: Colors.white,
                            letterSpacing: 0.3,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        SizedBox(height: 2),
                        Text(
                          _getFileInfo(),
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.white.withOpacity(0.8),
                            fontWeight: FontWeight.w500,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                  
                  // 操作按钮组
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // 重命名按钮
                      Container(
                        decoration: BoxDecoration(
                          color: Colors.orange.withOpacity(0.2),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: IconButton(
                          icon: Icon(Icons.edit_rounded, color: Colors.orange[300]),
                          tooltip: '重命名文档',
                          onPressed: () async {
                            await _showRenameDialog();
                          },
                        ),
                      ),
                      SizedBox(width: 8),
                      // 删除按钮
                      Container(
                        decoration: BoxDecoration(
                          color: Colors.red.withOpacity(0.2),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: IconButton(
                          icon: Icon(Icons.delete_rounded, color: Colors.red[300]),
                          tooltip: '删除文档',
                          onPressed: _showDeleteConfirmationDialog,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              
              SizedBox(height: 16),
              
              // 文档统计信息
              Container(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.15),
                  borderRadius: BorderRadius.circular(16),
                  border: Border.all(color: Colors.white.withOpacity(0.2)),
                ),
                child: IntrinsicHeight(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Expanded(child: _buildStatItem('格式', _getFileExtension(), Icons.description)),
                      Container(width: 1, color: Colors.white.withOpacity(0.3)),
                      Expanded(child: _buildStatItem('大小', _getFileSize(), Icons.storage)),
                      Container(width: 1, color: Colors.white.withOpacity(0.3)),
                      Expanded(child: _buildStatItem('状态', _isLoading ? '加载中' : '已加载', _isLoading ? Icons.hourglass_empty : Icons.check_circle)),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, color: Colors.white, size: 14),
        SizedBox(height: 4),
        Text(
          value,
          style: TextStyle(
            color: Colors.white,
            fontSize: 13,
            fontWeight: FontWeight.w700,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        Text(
          label,
          style: TextStyle(
            color: Colors.white.withOpacity(0.8),
            fontSize: 10,
            fontWeight: FontWeight.w500,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }

  IconData _getFileIcon() {
    if (_filePath == null) return Icons.description;
    final lowerPath = _filePath!.toLowerCase();
    if (lowerPath.endsWith('.pdf')) return Icons.picture_as_pdf;
    if (lowerPath.endsWith('.docx')) return Icons.description;
    if (lowerPath.endsWith('.md')) return Icons.code;
    if (lowerPath.endsWith('.txt')) return Icons.text_fields;
    return Icons.description;
  }

  String _getFileInfo() {
    if (_filePath != null) {
      return path.basename(_filePath!);
    }
    return '知识库文档';
  }

  String _getFileExtension() {
    if (_filePath == null) return 'DOC';
    final lowerPath = _filePath!.toLowerCase();
    if (lowerPath.endsWith('.pdf')) return 'PDF';
    if (lowerPath.endsWith('.docx')) return 'DOCX';
    if (lowerPath.endsWith('.md')) return 'MD';
    if (lowerPath.endsWith('.txt')) return 'TXT';
    return 'DOC';
  }

  String _getFileSize() {
    if (_filePath == null) return '未知';
    try {
      final file = File(_filePath!);
      if (file.existsSync()) {
        final bytes = file.lengthSync();
        if (bytes < 1024) return '${bytes}B';
        if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)}KB';
        return '${(bytes / (1024 * 1024)).toStringAsFixed(1)}MB';
      }
    } catch (e) {
      // 忽略错误
    }
    return '未知';
  }

  Widget _buildLoadingView() {
    return Container(
      padding: EdgeInsets.all(32),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                ),
                shape: BoxShape.circle,
                boxShadow: [
                  BoxShadow(
                    color: Color(0xFF667eea).withOpacity(0.3),
                    blurRadius: 20,
                    offset: Offset(0, 10),
                  ),
                ],
              ),
              child: Center(
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  strokeWidth: 3,
                ),
              ),
            ),
            SizedBox(height: 24),
            Text(
              '正在加载文档...',
              style: TextStyle(
                color: Colors.grey[600],
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
            SizedBox(height: 8),
            Text(
              'Tina正在为您准备文档内容',
              style: TextStyle(
                color: Colors.grey[500],
                fontSize: 14,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDocumentContent() {
    return SingleChildScrollView(
      padding: EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 文档信息卡片
          Container(
            margin: EdgeInsets.only(bottom: 20),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.08),
                  blurRadius: 16,
                  offset: Offset(0, 8),
                ),
              ],
            ),
            child: Padding(
              padding: EdgeInsets.all(20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        padding: EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [Color(0xFF667eea).withOpacity(0.1), Color(0xFF764ba2).withOpacity(0.1)],
                          ),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Icon(
                          Icons.info_outline,
                          color: Color(0xFF667eea),
                          size: 20,
                        ),
                      ),
                      SizedBox(width: 12),
                      Text(
                        '文档信息',
                        style: TextStyle(
                          fontWeight: FontWeight.w700,
                          fontSize: 18,
                          color: Colors.grey[800],
                          letterSpacing: 0.3,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 16),
                  _buildInfoRow('标题', _currentDocument['title'] ?? '未知标题'),
                  _buildInfoRow('文件名', _filePath != null ? path.basename(_filePath!) : "未知文件"),
                  if (_currentDocument['time'] != null)
                    _buildInfoRow('添加时间', _currentDocument['time']),
                  SizedBox(height: 12),
                  DocumentTagsWidget(document: _currentDocument),
                ],
              ),
            ),
          ),
          
          // 文档内容卡片
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.08),
                  blurRadius: 16,
                  offset: Offset(0, 8),
                ),
              ],
            ),
            child: Padding(
              padding: EdgeInsets.all(20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        padding: EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [Color(0xFF4CAF50).withOpacity(0.1), Color(0xFF8BC34A).withOpacity(0.1)],
                          ),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Icon(
                          Icons.article_outlined,
                          color: Color(0xFF4CAF50),
                          size: 20,
                        ),
                      ),
                      SizedBox(width: 12),
                      Text(
                        '文档内容',
                        style: TextStyle(
                          fontWeight: FontWeight.w700,
                          fontSize: 18,
                          color: Colors.grey[800],
                          letterSpacing: 0.3,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 20),
                  Container(
                    width: double.infinity,
                    padding: EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: Colors.grey[50],
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(color: Colors.grey[200]!),
                    ),
                    child: _isMarkdownFile 
                        ? _buildMarkdownView()
                        : Text(
                            _documentContent,
                            style: TextStyle(
                              fontSize: 14,
                              height: 1.6,
                              color: Colors.grey[700],
                            ),
                          ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 显示重命名对话框
  Future<void> _showRenameDialog() async {
    // 首先获取文档所属的分类
    final category = await _findDocumentCategory();
    if (category == null) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('无法确定文档分类，无法重命名'),
          backgroundColor: Colors.red[400],
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        ),
      );
      return;
    }

    // 获取当前文件名（去除扩展名）
    final currentTitle = _currentDocument['title'] ?? '未知文档';
    final fileExtension = path.extension(_filePath ?? '');
    String nameWithoutExtension = currentTitle;
    
    // 如果标题包含扩展名，则去除
    if (nameWithoutExtension.endsWith(fileExtension) && fileExtension.isNotEmpty) {
      nameWithoutExtension = nameWithoutExtension.substring(0, nameWithoutExtension.length - fileExtension.length);
    }

    final controller = TextEditingController(text: nameWithoutExtension);

    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        title: Row(
          children: [
            Container(
              padding: EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Colors.orange[50],
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(
                Icons.edit_rounded,
                color: Colors.orange[600],
                size: 24,
              ),
            ),
            SizedBox(width: 12),
            Text(
              '重命名文档',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.w700,
                color: Colors.grey[800],
              ),
            ),
          ],
        ),
        content: Container(
          width: double.maxFinite,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '请输入新的文档名称：',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.grey[700],
                  fontWeight: FontWeight.w500,
                ),
              ),
              SizedBox(height: 16),
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(color: Colors.orange[200]!),
                  color: Colors.orange[50],
                ),
                child: TextField(
                  controller: controller,
                  decoration: InputDecoration(
                    labelText: '文档名称',
                    hintText: '输入新的文档名称',
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                    labelStyle: TextStyle(color: Colors.orange[600]),
                    hintStyle: TextStyle(color: Colors.grey[400]),
                  ),
                  autofocus: true,
                  maxLength: 50,
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                    color: Colors.grey[800],
                  ),
                ),
              ),
              SizedBox(height: 8),
              Text(
                '文件类型: $fileExtension',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[500],
                ),
              ),
            ],
          ),
        ),
        actions: [
          Container(
            height: 44,
            child: TextButton(
              onPressed: () => Navigator.pop(context),
              style: TextButton.styleFrom(
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                backgroundColor: Colors.grey[100],
              ),
              child: Text(
                '取消',
                style: TextStyle(
                  color: Colors.grey[700],
                  fontWeight: FontWeight.w600,
                  fontSize: 14,
                ),
              ),
            ),
          ),
          SizedBox(width: 8),
          Container(
            height: 44,
            child: ElevatedButton(
              onPressed: () async {
                final newName = controller.text.trim();
                if (newName.isEmpty) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('文档名称不能为空')),
                  );
                  return;
                }
                
                Navigator.pop(context);
                await _performRename(category, newName);
              },
              style: ElevatedButton.styleFrom(
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                backgroundColor: Colors.orange[600],
                elevation: 0,
              ),
              child: Text(
                '确认',
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w600,
                  fontSize: 14,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 查找文档所属的分类
  Future<String?> _findDocumentCategory() async {
    try {
      final categories = await widget.fileServe.getCategories();
      for (final category in categories) {
        final documents = await widget.fileServe.getKnowledgeCardInfo();
        for (final categoryInfo in documents) {
          if (categoryInfo['category'] == category) {
            final docs = categoryInfo['documents'] as List;
            for (final doc in docs) {
              if (doc['path'] == _currentDocument['path']) {
                return category;
              }
            }
          }
        }
      }
      return null;
    } catch (e) {
      print('查找文档分类失败: $e');
      return null;
    }
  }

  /// 执行重命名操作
  Future<void> _performRename(String category, String newName) async {
    try {
      if (!mounted) return;
      
      // 显示美化的加载指示器
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => Dialog(
          backgroundColor: Colors.transparent,
          elevation: 0,
          child: Center(
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 24),
              padding: EdgeInsets.all(32),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    Colors.white,
                    Colors.orange[50]!,
                  ],
                ),
                borderRadius: BorderRadius.circular(24),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 20,
                    offset: Offset(0, 10),
                  ),
                  BoxShadow(
                    color: Colors.orange.withOpacity(0.1),
                    blurRadius: 40,
                    offset: Offset(0, 20),
                  ),
                ],
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 美化的加载动画
                  Container(
                    width: 60,
                    height: 60,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [Colors.orange[400]!, Colors.orange[600]!],
                      ),
                      shape: BoxShape.circle,
                      boxShadow: [
                        BoxShadow(
                          color: Colors.orange.withOpacity(0.3),
                          blurRadius: 15,
                          offset: Offset(0, 5),
                        ),
                      ],
                    ),
                    child: Center(
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        strokeWidth: 3,
                      ),
                    ),
                  ),
                  SizedBox(height: 24),
                  // 美化的文本
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        Icons.edit_rounded,
                        color: Colors.orange[600],
                        size: 20,
                      ),
                      SizedBox(width: 8),
                      Text(
                        '正在重命名文档',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: Colors.grey[800],
                          letterSpacing: 0.5,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 8),
                  Text(
                    'Tina正在为您处理...',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[600],
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );

      final result = await widget.fileServe.renameFile(category, newName, _currentDocument['path']);
      
      if (!mounted) return;
      Navigator.pop(context); // 关闭加载对话框

      if (result != null) {
        // 更新本地文档数据
        setState(() {
          _currentDocument = Map<String, dynamic>.from(result.$1[result.$2]);
          _filePath = _currentDocument['path'];
        });

        // 重新加载文档内容
        await _loadDocumentContent();

        if (!mounted) return;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                Icon(Icons.check_circle, color: Colors.white),
                SizedBox(width: 8),
                Text('文档重命名成功'),
              ],
            ),
            backgroundColor: Colors.green[500],
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
        );
        
        // 返回上一页并通知刷新
        Navigator.pop(context, true);
      } else {
        if (!mounted) return;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                Icon(Icons.error, color: Colors.white),
                SizedBox(width: 8),
                Text('重命名失败，请重试'),
              ],
            ),
            backgroundColor: Colors.red[500],
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
        );
      }
    } catch (e) {
      if (!mounted) return;
      
      // 确保关闭加载对话框
      try {
        Navigator.pop(context);
      } catch (e) {}
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: [
              Icon(Icons.error, color: Colors.white),
              SizedBox(width: 8),
              Expanded(child: Text('重命名失败: $e')),
            ],
          ),
          backgroundColor: Colors.red[500],
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        ),
      );
    }
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 6),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label:',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: Colors.grey[600],
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[800],
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPdfViewer() {
    if (_filePath == null) {
      return Container(
        padding: EdgeInsets.all(32),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                padding: EdgeInsets.all(24),
                decoration: BoxDecoration(
                  color: Colors.red[50],
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(color: Colors.red[200]!),
                ),
                child: Icon(
                  Icons.error_outline,
                  size: 48,
                  color: Colors.red[400],
                ),
              ),
              SizedBox(height: 16),
              Text(
                '无法加载PDF文件',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey[700],
                ),
              ),
              SizedBox(height: 8),
              Text(
                '文件路径不存在或已损坏',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[500],
                ),
              ),
            ],
          ),
        ),
      );
    }
    
    return Padding(
      padding: EdgeInsets.all(24),
      child: EnhancedPdfViewer(
        filePath: _filePath!,
        docId: _currentDocument['doc_id'],
        fileServe: FileServe(),
        title: _currentDocument['title'],
      ),
    );
  }
  
  Future<void> _openFileWithSystemApp() async {
    try {
      if (_filePath != null) {
        final file = File(_filePath!);
        if (await file.exists()) {
          // 使用系统应用打开PDF文件
          // 注意：这里需要使用url_launcher包（已在pubspec.yaml中）
          final uri = Uri.file(file.path);
          final canLaunch = await canLaunchUrl(uri);
          if (canLaunch) {
            await launchUrl(uri);
          } else {
            if (!mounted) return;
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('无法打开PDF文件：找不到相应的应用程序')),
            );
          }
        } else {
          if (!mounted) return;
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('文件不存在或已被删除')),
          );
        }
      }
    } catch (e) {
      print('打开PDF文件失败: $e');
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('打开PDF文件失败: $e')),
      );
    }
  }

  Widget _buildDocxViewer() {
    if (_filePath == null) {
      return Container(
        padding: EdgeInsets.all(32),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                padding: EdgeInsets.all(24),
                decoration: BoxDecoration(
                  color: Colors.orange[50],
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(color: Colors.orange[200]!),
                ),
                child: Icon(
                  Icons.error_outline,
                  size: 48,
                  color: Colors.orange[400],
                ),
              ),
              SizedBox(height: 16),
              Text(
                '无法加载DOCX文件',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey[700],
                ),
              ),
              SizedBox(height: 8),
              Text(
                '文件路径不存在或已损坏',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[500],
                ),
              ),
            ],
          ),
        ),
      );
    }

    return Padding(
      padding: EdgeInsets.all(24),
      child: Column(
        children: [
          // DOCX查看器标题卡片
          Container(
            margin: EdgeInsets.only(bottom: 20),
            padding: EdgeInsets.all(20),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Colors.orange[100]!,
                  Colors.orange[50]!,
                ],
              ),
              borderRadius: BorderRadius.circular(20),
              border: Border.all(color: Colors.orange[200]!),
              boxShadow: [
                BoxShadow(
                  color: Colors.orange.withOpacity(0.1),
                  blurRadius: 16,
                  offset: Offset(0, 8),
                ),
              ],
            ),
            child: Row(
              children: [
                Container(
                  padding: EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.orange[600],
                    borderRadius: BorderRadius.circular(16),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.orange[600]!.withOpacity(0.3),
                        blurRadius: 8,
                        offset: Offset(0, 4),
                      ),
                    ],
                  ),
                  child: Icon(
                    Icons.description,
                    color: Colors.white,
                    size: 24,
                  ),
                ),
                SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'DOCX文档查看器',
                        style: TextStyle(
                          fontWeight: FontWeight.w700,
                          fontSize: 18,
                          color: Colors.orange[800],
                          letterSpacing: 0.3,
                        ),
                      ),
                      SizedBox(height: 4),
                      Text(
                        path.basename(_filePath!),
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.orange[700],
                          fontWeight: FontWeight.w500,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          
          // DOCX查看器主体
          Expanded(
            child: EnhancedDocxViewer(
              filePath: _filePath!,
              docId: _currentDocument['doc_id'],
              fileServe: FileServe(),
              title: _currentDocument['title'],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMarkdownView() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: MarkdownBody(
        data: _documentContent,
        selectable: true,
        styleSheet: MarkdownStyleSheet(
          h1: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.w700,
            color: Color(0xFF667eea),
            height: 1.3,
          ),
          h2: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w600,
            color: Color(0xFF764ba2),
            height: 1.3,
          ),
          h3: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: Colors.grey[700],
            height: 1.3,
          ),
          p: TextStyle(
            fontSize: 14,
            height: 1.6,
            color: Colors.grey[700],
            fontWeight: FontWeight.w400,
          ),
          code: TextStyle(
            fontSize: 13,
            fontFamily: 'monospace',
            backgroundColor: Colors.grey[100],
            color: Color(0xFF667eea),
          ),
          codeblockDecoration: BoxDecoration(
            color: Colors.grey[50],
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: Colors.grey[300]!),
          ),
          blockquote: TextStyle(
            fontSize: 14,
            color: Colors.grey[600],
            fontStyle: FontStyle.italic,
          ),
          blockquoteDecoration: BoxDecoration(
            color: Colors.blue[50],
            borderRadius: BorderRadius.circular(8),
            border: Border(
              left: BorderSide(
                color: Color(0xFF667eea),
                width: 4,
              ),
            ),
          ),
          listBullet: TextStyle(
            color: Color(0xFF667eea),
            fontSize: 14,
          ),
          tableHead: TextStyle(
            fontWeight: FontWeight.w600,
            color: Colors.grey[800],
          ),
          tableBody: TextStyle(
            fontSize: 14,
            color: Colors.grey[700],
          ),
        ),
        onTapLink: (text, href, title) {
          if (href != null) {
            _launchUrl(href);
          }
        },
      ),
    );
  }
  
  Future<void> _launchUrl(String urlString) async {
    try {
      final uri = Uri.parse(urlString);
      final canLaunch = await canLaunchUrl(uri);
      if (canLaunch) {
        await launchUrl(uri);
      } else {
        if (!mounted) return;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('无法打开链接: $urlString')),
        );
      }
    } catch (e) {
      print('打开链接失败: $e');
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('打开链接失败: $e')),
      );
    }
  }

  /// 显示删除确认对话框
  Future<void> _showDeleteConfirmationDialog() async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        title: Row(
          children: [
            Container(
              padding: EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Colors.red[50],
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(
                Icons.warning_rounded,
                color: Colors.red[600],
                size: 24,
              ),
            ),
            SizedBox(width: 12),
            Text(
              '确认删除',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.w700,
                color: Colors.grey[800],
              ),
            ),
          ],
        ),
        content: Container(
          padding: EdgeInsets.symmetric(vertical: 8),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '您确定要删除此文档吗？',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.grey[700],
                  fontWeight: FontWeight.w500,
                ),
              ),
              SizedBox(height: 8),
              Container(
                padding: EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.red[50],
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(color: Colors.red[200]!),
                ),
                child: Row(
                  children: [
                    Icon(Icons.info_outline, color: Colors.red[600], size: 16),
                    SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        '此操作不可撤销',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.red[700],
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        actions: [
          Container(
            height: 44,
            child: TextButton(
              onPressed: () => Navigator.pop(context, false),
              style: TextButton.styleFrom(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                backgroundColor: Colors.grey[100],
              ),
              child: Text(
                '取消',
                style: TextStyle(
                  color: Colors.grey[700],
                  fontWeight: FontWeight.w600,
                  fontSize: 14,
                ),
              ),
            ),
          ),
          SizedBox(width: 8),
          Container(
            height: 44,
            child: TextButton(
              onPressed: () => Navigator.pop(context, true),
              style: TextButton.styleFrom(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                backgroundColor: Colors.red[600],
              ),
              child: Text(
                '删除',
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w600,
                  fontSize: 14,
                ),
              ),
            ),
          ),
        ],
      ),
    );

    if (result == true) {
      await _deleteDocument();
    }
  }

  /// 删除文档
  Future<void> _deleteDocument() async {
    try {
      setState(() {
        _isLoading = true;
      });

      final docId = widget.document['doc_id'];
      if (docId == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('无法删除文档：缺少文档ID')),
        );
        setState(() {
          _isLoading = false;
        });
        return;
      }

      // 从Dify知识库中删除文档
      final deleteResult = await widget.difyKnowledge.deleteDocument(docId);
      
      // 从所有分类中删除文档记录
      await widget.fileServe.removeDocumentFromCategories(docId);
      
      // 删除本地文件
      if (_filePath != null) {
        final file = File(_filePath!);
        if (await file.exists()) {
          try {
            await file.delete();
            print('成功删除本地文件: $_filePath');
          } catch (e) {
            print('删除本地文件失败: $e');
          }
        }
      }

      if (!mounted) return;

      if (deleteResult['result'] == 'success' || 
          (deleteResult.containsKey('status') && deleteResult['status'] == 'success')) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('文档已成功删除')),
        );
        // 返回上一页
        Navigator.pop(context, true); // 传递true表示文档已被删除
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('删除文档失败: ${deleteResult['message'] ?? "未知错误"}')),
        );
        setState(() {
          _isLoading = false;
        });
      }
    } catch (e) {
      print('删除文档时发生错误: $e');
      
      if (!mounted) return;
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('删除文档失败: $e')),
      );
      setState(() {
        _isLoading = false;
      });
    }
  }
}

// 添加搜索代理类
class CustomSearchDelegate extends SearchDelegate<String> {
  final DifyKnowledgeDatabase difyKnowledge;
  final FileServe fileServe;

  CustomSearchDelegate(this.difyKnowledge, this.fileServe);

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () {
          query = '';
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () {
        close(context, '');
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    if (query.trim().isEmpty) return Container();
    
    return FutureBuilder(
      future: difyKnowledge.query(query),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(child: CircularProgressIndicator());
        }
        
        if (snapshot.hasError) {
          return Center(child: Text('搜索出错: ${snapshot.error}'));
        }
        
        final results = snapshot.data as List<dynamic>? ?? [];
        
        if (results.isEmpty) {
          return Center(child: Text('没有找到相关内容'));
        }
        
        return ListView.builder(
          itemCount: results.length,
          itemBuilder: (context, index) {
            final item = results[index];
            return ListTile(
              title: Text(item['title'] ?? '未知标题'),
              subtitle: Text(item['content'] ?? ''),
              onTap: () {
                // 处理点击搜索结果，确保传递fileServe参数
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => SearchResultsPage(
                      query: query,
                      difyKnowledge: difyKnowledge,
                      fileServe: fileServe,
                    ),
                  ),
                );
              },
            );
          },
        );
      },
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    // 简单实现，可以返回空容器或历史搜索建议
    return Container();
  }
} 